package com.dindang.propertyfee.mvp.presenter;

import android.app.Application;
import android.view.View;
import android.widget.PopupWindow;

import com.alibaba.android.arouter.launcher.ARouter;
import com.dindang.propertyfee.app.AppConst;
import com.dindang.propertyfee.app.utils.TextViewUtils;
import com.dindang.propertyfee.mvp.model.entity.BaseResponse;
import com.dindang.propertyfee.mvp.model.entity.PropertyCharge;
import com.dindang.propertyfee.mvp.ui.adapter.custom.RecentBillViewAdapter;
import com.dindang.propertyfee.mvp.ui.widget.SpinerPopDateRange;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import in.srain.cube.views.ptr2.PtrDefaultHandler2;
import in.srain.cube.views.ptr2.PtrFrameLayout;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;

import javax.inject.Inject;

import com.dindang.propertyfee.mvp.contract.FeeList2Contract;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;

import java.util.ArrayList;
import java.util.List;


@ActivityScope
public class FeeList2Presenter extends BasePresenter<FeeList2Contract.Model, FeeList2Contract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private int LIMIT = 10;
    private SpinerPopDateRange mSpinerPopDateRange;
    private PropertyCharge.RecentBillParam mParam = new PropertyCharge.RecentBillParam(LIMIT);
    private List<PropertyCharge.RecentBill.Rows> mRowList = new ArrayList<>();
    private RecentBillViewAdapter mAdapter;

    @Inject
    public FeeList2Presenter(FeeList2Contract.Model model, FeeList2Contract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        mRootView.getTvTotal().setText(TextViewUtils.setFeeHJ(mApplication, 0, 0));
        initAdapter();
        initPop();
        initListener();
    }

    public void initParam(String title){
        switch (title) {
            case "今日到期":
                mParam.setStartNum("-1", "1");
                break;
            case "明日到期":
                mParam.setStartNum("0", "2");
                break;
            case "7日到期":
                mParam.setStartNum("-1", "7");
                break;
            case "30日到期":
                mParam.setStartNum("-1", "30");
                break;
            case "已逾期":
                mParam.setStartNum("-9999999", "0");
                break;
            case "条件查找":
                mRootView.getIvSort().setVisibility(View.GONE);
                mParam = (PropertyCharge.RecentBillParam) mRootView.getActivity().getIntent().getSerializableExtra(AppConst.PARAM_DATA);
                break;
        }

        mRootView.getPtrclassicframelayout().autoRefresh(true);
    }

    private void initPop() {
        mSpinerPopDateRange = new SpinerPopDateRange(mRootView.getActivity(), new SpinerPopDateRange.OnClickListener() {
            @Override
            public void onClick(String rangeName) {
                String title = mRootView.getTvTitle().getText().toString().trim();
                if(!title.equals(rangeName)){// 判断当前页面上数据是否是已选择的数据
                    mRootView.getTvTitle().setText(rangeName);
                    initParam(rangeName);
                }
                mSpinerPopDateRange.dismiss();
            }
        });
        mSpinerPopDateRange.setOnDismissListener(dismissListener);
    }

    private void initAdapter() {
        mAdapter = new RecentBillViewAdapter(mRowList, new RecentBillViewAdapter.OnClickListener() {
            @Override
            public void onClick(int position) {
                PropertyCharge.RecentBill.Rows rows = mRowList.get(position);
                ARouter.getInstance().build("/propertyfee/activity/ReceivableDetailActivity")
                        .withString(AppConst.ID, rows.c_nodedate_id)
                        .withString(AppConst.RECEIVABLEDETAIL_ADDRESS, rows.bName + "/" + rows.addr)
                        .withString(AppConst.RECEIVABLEDETAIL_NAME_TEL, rows.custName + "/" + rows.c_telphone)
                        .withString(AppConst.RECEIVABLEDETAIL_TEL_PHONE, rows.c_telphone)
                        .navigation();
            }
        });
        mRootView.getRecyclerview().setAdapter(mAdapter);
    }

    private void initListener() {
        mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.BOTH);
        mRootView.getPtrclassicframelayout().disableWhenHorizontalMove(true);
        mRootView.getPtrclassicframelayout().setLastUpdateTimeRelateObject(this);
        mRootView.getPtrclassicframelayout().setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                queryRecentBill();
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mParam.page = 0;
                queryRecentBill();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return super.checkCanDoRefresh(frame, content, header);
            }

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return super.checkCanDoLoadMore(frame, content, footer);
            }
        });
    }

    private void queryRecentBill(){
        if(AppConst.DUE_TO_TITLE_ADVANCED.equals(mRootView.getActivity().getIntent().getStringExtra(AppConst.DUE_TO))){
            queryRecentBill3();
        }else{
            queryRecentBill2();
        }
    }

    /**
     * 查询近期账单,更多点进去
     */
    private void queryRecentBill2(){
        mParam.corpid = BaseAppConst.accountInfo.getCorpId();
        mParam.rows = 10;
        mModel.queryRecentBill(mParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {

        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<PropertyCharge.RecentBill>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<PropertyCharge.RecentBill> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                setData(response);
            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
                mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_ERROR);
                if(mRootView.getPtrclassicframelayout().isRefreshing()){
                    mRootView.getPtrclassicframelayout().refreshComplete();
                }
            }
        });
    }

    /**
     * 条件搜索
     */
    private void queryRecentBill3(){
        mParam.corpid = BaseAppConst.accountInfo.getCorpId();
        mModel.queryRecentBill2(mParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {
//            mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_ERROR);
            if(mRootView.getPtrclassicframelayout().isRefreshing()){
                mRootView.getPtrclassicframelayout().refreshComplete();
            }
        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<PropertyCharge.RecentBill>>(mErrorHandler) {
            @Override
            public void onError(Throwable t) {
                super.onError(t);
            }

            @Override
            public void onNext(BaseResponse<PropertyCharge.RecentBill> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                setData(response);
            }
        });
    }

    /**
     * 设置列表数据
     * @param response
     */
    private void setData(BaseResponse<PropertyCharge.RecentBill> response){
        if(mRootView.getPtrclassicframelayout().isRefreshing()){
            mRootView.getPtrclassicframelayout().refreshComplete();
        }
        if(!response.isSuccess()){
            ArmsUtils.makeText(mApplication, response.getStatuMsg());
            mRootView.getEmptyLayout().ERROR_TIP = response.getStatuMsg();
            mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_ERROR);
            return;
        }

        mRootView.getTvTotal().setText(TextViewUtils.setFeeHJ(mApplication, response.getData().pageData.total, response.getData().sumAmount));

        if(response.getData().pageData.rows.size() < LIMIT){
            mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.REFRESH);
        }else{
            mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.BOTH);
            mParam.page++;
        }

        if(mParam.page == 0){
            mRowList.clear();
        }
        mRowList.addAll(response.getData().pageData.rows);
        if(mRowList.size() == 0){
            mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_NO_DATA);
        }else{
            mRootView.getEmptyLayout().hide();
        }
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 弹出框
     */
    public void sortDialog() {
        if(mSpinerPopDateRange.isShowing()){
            mSpinerPopDateRange.dismiss();
        }else{
            mSpinerPopDateRange.showAsDropDown(mRootView.getIvSort());
        }
    }

    /**
     * 监听popupwindow取消
     */
    private PopupWindow.OnDismissListener dismissListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            mSpinerPopDateRange.dismiss();
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mSpinerPopDateRange = null;
        this.mParam = null;
        this.mRowList = null;
    }
}
